package com.itheima.controller.order;

import com.github.pagehelper.PageInfo;
import com.itheima.controller.BaseServlet;
import com.itheima.domain.Orders;
import com.itheima.service.OrdersService;
import com.itheima.utils.BeanUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@WebServlet("/ordersServlet/*")
public class OrdersServlet extends BaseServlet {
    protected void list(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        List<Orders> list = ordersService.findAll(req.getParameter("pageNum"), req.getParameter("pageSize"));
        System.out.println(list.get(0).getId()+"LLLLLL");
        PageInfo<Orders> pageInfo = new PageInfo<>(list);
        /*向域中添加数据*/
        req.setAttribute("page", pageInfo);
        req.getRequestDispatcher("/pages/orders-list.jsp").forward(req, resp);
    }

    /*保存数据*/
    protected void save(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       // 获取数据 并封装在实体类中
        Orders orders = BeanUtil.fillBean(req, Orders.class, "yyyy-MM-dd");
        //使用UUID获取唯一值,用于主键Id
        String s = UUID.randomUUID().toString().replaceAll("-", "");
        orders.setId(s);
        System.out.println(orders);
        ordersService.ordersAdd(orders);
        list(req, resp);
    }

    /*根据id查询数据,用于数据的回显*/
    protected void toAll(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Orders orders = ordersService.findById(req.getParameter("id"));

        System.out.println("==================================");
        System.out.println(orders);

        req.setAttribute("orders", orders);
        req.getRequestDispatcher("/pages/orders-show.jsp").forward(req, resp);
    }

    /*修改数据*/
    /*protected void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Orders orders = BeanUtil.fillBean(req, Orders.class);
        orders.setId(req.getParameter("id"));
        ordersService.update(orders);
        findAll(req, resp);
    }*/

    /*批量删除数据*/
    protected void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String ids1 = req.getParameter("id");
        String[] ids = ids1.split(",");
        ordersService.delete(ids);
        list(req, resp);
    }

}
